package base.http.rxandroid

import android.app.Activity
import android.content.Context
import android.os.Looper
import android.util.Log
import android.widget.Toast
import base.utils.ActivityManager
import base.utils.NetWorkUtils
import base.utils.SysUtils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import io.reactivex.Observer
import io.reactivex.annotations.NonNull
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException

/**
 * @author njmsir
 * Created by njmsir on 2017/9/5.
 */
abstract class CustomObserver<T> : Observer<T> {

    companion object {
        val TAG = "observer_exception"
    }

    private lateinit var gson: Gson
    private var customConsumer: CustomConsumer? = null
    private lateinit var context: Context

    constructor(context: Context) : this(null, context)
    constructor(customConsumer: CustomConsumer?, context: Context) {
        this.context = context
        gson = Gson()
        if (customConsumer != null) {
            this.customConsumer = customConsumer
        }
    }

    override fun onSubscribe(@NonNull d: Disposable) {
//        CompositeDisposableUtilsV2.getInstance.instance.add(d)
    }


    override fun onComplete() {
        customConsumer?.dismiss()
    }

    override fun onError(@NonNull e: Throwable) {
        try {
            if (Looper.myLooper() != Looper.getMainLooper()) return
            if (!NetWorkUtils.isNetWorkAvailable(context)) Toast.makeText(context, "网络已断开", Toast.LENGTH_SHORT).show()
            else {
                if (e is ConnectException) {
                    Toast.makeText(context, "服务器忙", Toast.LENGTH_SHORT).show()
                } else if (e is HttpException) {
                    try {
                        val errorText = e.response()!!.errorBody()?.string()
                    } catch (e: JsonSyntaxException) {
                        Toast.makeText(context, "出错了~", Toast.LENGTH_SHORT).show()
                    } catch (e1: IOException) {
                        Toast.makeText(context, "好像发生了点什么~", Toast.LENGTH_SHORT).show()
                    }
                } else if (e is SocketTimeoutException || e is SocketException) {
                    Toast.makeText(context, "网络链接超时", Toast.LENGTH_SHORT).show()
                } else if (e!!.message != null && SysUtils.isContainChinese(e.message!!)) {
                    Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
                }
            }
            e!!.printStackTrace()
            Log.e(TAG, "CustomObserver onError: ", e)
            customConsumer?.dismiss()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "CustomObserver onError: ", e)
        }
    }

}